<?php

namespace App\Repositories\Eloquent\Exm;

use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;

class RecruitRepository extends Repository
{

    /**
     * @param App
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Exm\Recruit';
    }


    public function index($type = '')
    {
        $result = $this->model->orderBy('id', 'asc')->get();

        return $result;
    }


    public function store($request)
    {
        $idcard = $request->idcard;
        $age = $this->ageVerification($idcard);
        if($age < 60)
            return $this->responseFail(500, '年龄不符合投稿要求');

        //重复投稿检测

        $result = $this->findBy('idcard',$idcard);

        if(!!$result)
            return $this->responseFail(500, '重复投稿');

        $result = $this->findBy('mobile',$request->mobile);
        if(!!$result)
            return $this->responseFail(500, '重复投稿');

        \DB::beginTransaction();
        try {
            if( $request->hasFile('files') ){

                $dir = public_path().'/uploads/cslnbj/';

                $file = $request->file('files');

                $entension = $file->getClientOriginalExtension();
                if( ($entension !== 'doc') && ($entension !== 'docx') )
                    return $this->responseFail(500, '稿件格式不正确');

                $filename = $file->getClientOriginalName();

                $file->move($dir,$filename);

                $fullname = '/uploads/cslnbj/'.$filename;

                //写库
                $attach = new \App\Models\Exm\Recruit;
                $attach->name = $request->name;
                $attach->mobile = $request->mobile;
                $attach->idcard = $idcard;
                $attach->file = $fullname;
                $attach->save();

            }
            \DB::commit();

            return $this->responseSuccess('投稿成功', $attach, route('wx.settle.recruit'));

        } catch (\Exception $e) {
            \DB::rollback();
            return $this->responseFail(500, '投稿失败');
        }
    }


    private function ageVerification($idcard)
    {
         $ddate = strtotime(substr($idcard, 6, 8));

         if($ddate === false){
          return false;
         }

         list($y1,$m1,$d1) = explode("-",date("Y-m-d",$ddate));

         $now_time = strtotime("now");

         list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now_time));
         $age = $y2 - $y1;
         if((int)($m2.$d2) < (int)($m1.$d1)){
          $age -= 1;
         }
         return $age;
        }


}